//
//  GrowthViewController.m
//  leo
//
//  Created by 常艳 on 15/9/17.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "GrowthViewController.h"
#import "ThemeViewController.h"
#import "TaskViewController.h"
#import "common.h"
#import "GrowDataManager.h"
#import "DataManager.h"
#import "Tooler.h"
#import "GrowManager.h"
#import "ExplocyViewController.h"
#import "AppDelegate.h"
@interface GrowthViewController ()
@property (nonatomic,strong) GrowDataManager *growDataManager;
@property (nonatomic,strong) Growth *growthData;
@property (nonatomic,strong) Growth *todayGrowthData;
@property (nonatomic,strong) DataManager *dataManager;
@property (nonatomic,strong) User *user;
@property (nonatomic,strong) Watch *selectWatch;
@property (nonatomic,strong) GrowManager *growManager;
@end

@implementation GrowthViewController
@synthesize growDataManager;
@synthesize growthData;
@synthesize dataManager;
@synthesize user;
@synthesize selectWatch;
@synthesize growManager;
@synthesize todayGrowthData;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UITabBarItem *item = [[UITabBarItem alloc]initWithTitle:@"成长" image:[UIImage imageNamed:@"tb_grow_icon_normal@2x"] tag:3];
        [item setSelectedImage:[UIImage imageNamed:@"tb_grow_icon_hl@2x"]];
        self.tabBarItem = item;

    }
    return self;
}
-(void)dealloc
{
    [self removeObservers];
    growDataManager=NULL;
    growthData=NULL;
    dataManager=NULL;
    user=NULL;
    selectWatch=NULL;
    growManager=NULL;
    todayGrowthData=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.isSyncFinish=YES;
    // Do any additional setup after loading the view from its nib.
    [self registerObservers];
    [self initProgerssView];
    [self initDataProxy];
    [self downLoadGrowthData];

}

-(void)initProgerssView
{
    self.progressView.transform = CGAffineTransformMakeScale(1.0f,8.0f);
    [self.progressView.layer setMasksToBounds:YES];
    self.progressView.layer.cornerRadius=10;
    self.progressView.clipsToBounds=YES;
}
-(void)initDataProxy
{
    dataManager=[[DataManager alloc] init];
    if(dataManager==NULL)
        return;
    user=[User sharedSingleton];
    if(user==NULL)
        return;
    growDataManager=[[GrowDataManager alloc] init];
    if(growDataManager==NULL)
        return;
    growManager=[[GrowManager alloc] init];
    if(growManager==NULL)
        return;
}
-(void)initUiData
{
     NSArray *levelArr = @[@"6",@"16",@"31",@"51",@"81",@"121",@"171",@"231",@"301",@"381",@"471",@"571",@"681",@"801"];
   
    if(growDataManager==NULL)
        return;
    selectWatch=[dataManager getActiveWatch:user.uid];
    if(selectWatch==NULL)
        return;
    growthData=[growDataManager getLatestGrowth:selectWatch.deviceUid];
    if(growthData==NULL)
        return;
     NSString *levelStr=[NSString stringWithFormat:@"LV.%d",[Tooler getLevelNum:growthData.semp]];
    if(growthData.semp>0)
    {
        self.levelLable.text=levelStr;
    }
    
    
    switch ([selectWatch.themeId intValue]) {
        case 1:
            _themeName.text = @"遨游太空";
            break;
            
        default:
            _themeName.text = @"生如夏花";
            break;
    }


    if (growthData.semp >= 1) {
        int level = [Tooler getLevelNum:growthData.semp];
        NSString *totalLevel = levelArr[level - 1];
        self.levelValue.text=[NSString stringWithFormat:@"%d/%@",growthData.semp,totalLevel];

    }
  
    float progressValue=[Tooler getProgressRate:growthData.semp];
    [self.progressView setProgress:progressValue];
    
    
    todayGrowthData=[growDataManager getTodayGrowth:selectWatch.deviceUid];
    if(todayGrowthData==NULL)
        return;
    if(todayGrowthData.emp>0)
        self.growLable.text=[NSString stringWithFormat:@"%d",todayGrowthData.emp];

}
-(void)initThemeUi
{
    if(selectWatch==NULL||growDataManager==NULL)
        return;
    selectWatch=[dataManager getActiveWatch:user.uid];
    Theme *theme=[growDataManager getThemeInfo:selectWatch.themeId];
    if(theme==NULL)
        return;
    if(theme.themePicUrl!=NULL&&![theme.themePicUrl isEqualToString:@"(null)"])
        self.himg.image=[UIImage imageNamed:theme.themePicUrl] ;
    int level=0;
    Growth *growth=[growDataManager getLatestGrowth:selectWatch.deviceUid];
    if(growth!=NULL)
    {
        level=[Tooler getLevelNum:growth.semp];
        if(level>15)
            level=15;
    }
    ThemeLevel *levelInfo=[growDataManager getLevelInfo:selectWatch.themeId level:level];
    if(levelInfo==NULL)
        return;
    if(levelInfo.levelUrl!=NULL&&![levelInfo.levelUrl isEqualToString:@"(null)"])
        self.levelimg.image=[UIImage imageNamed:levelInfo.levelUrl];
   
    _topView.layer.borderColor =  [UIColor colorWithRed:0.79 green:0.88 blue:0.92 alpha:1].CGColor;
    _topView.layer.borderWidth = 1.0;

    _secView.layer.borderColor =  [UIColor colorWithRed:0.79 green:0.88 blue:0.92 alpha:1].CGColor;
    _secView.layer.borderWidth = 1.0;
    _thirdView.layer.borderColor =  [UIColor colorWithRed:0.79 green:0.88 blue:0.92 alpha:1].CGColor;
    _thirdView.layer.borderWidth = 1.0;
}
-(void)updateData
{
    if(self.isSyncFinish==YES)
    {
        self.isSyncFinish=NO;
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,getManagerPhotos,queue is null",DATAMANAGER_TAG);
        return;
    }
    dispatch_async(queue, ^{
        if(growManager==NULL)
            return;
        selectWatch=[dataManager getActiveWatch:user.uid];
        if(selectWatch==NULL)
            return;
        [growManager getGrowthData:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                [self initUiData];
                [self initThemeUi];
            }
            else
            {
                //[Tooler showHttpMsg:result description:description msg:@"获取成长值失败"];
            }
        }];
        
        [growManager getWatchTheme:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                [self initThemeUi];
            }
            else
            {
                //[Tooler showHttpMsg:result description:description msg:@"获取手表主题失败"];
            }
            self.isSyncFinish=YES;
        } deviceUid:selectWatch.deviceUid];

    });
    }
}
-(void)downLoadGrowthData
{
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,getManagerPhotos,queue is null",DATAMANAGER_TAG);
        return;
    }
    dispatch_async(queue, ^{
        if(growManager==NULL)
            return;
        long updateTime=[Tooler getGrowthUpdateTime];
        if(updateTime>0)
        {
            
        }
        else
        {
            [growManager getPresetTasks:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                
            }];
            [growManager getExpPolicy:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                
            }];
            [Tooler updateGrowthUpdateTime:(long)[[Tooler getTS] longLongValue]];
        }

    });



}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    if(self.motherTabViewController!=NULL)
    {
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL&&mydelegate.isAdmin==YES)
        {
            self.motherTabViewController.navigationItem.rightBarButtonItem=nil;
            UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"rengwu@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(openTask)];
            [self.motherTabViewController.navigationItem setRightBarButtonItem:rightButton];
            rightButton=NULL;
          
            UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhuti@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(openTheme)];
            [self.motherTabViewController.navigationItem setLeftBarButtonItem:leftButton];
            leftButton=NULL;
        }
    }

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self updateData];
    [self initUiData];
    [self initThemeUi];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    if(self.motherTabViewController!=NULL)
    {
        self.motherTabViewController.navigationItem.rightBarButtonItem=NULL;
        self.motherTabViewController.navigationItem.leftBarButtonItem=NULL;
    }

}
-(void)openTheme
{
    ThemeViewController *themeViewController=[[ThemeViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:themeViewController animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(void)openTask
{
    TaskViewController *taskViewController=[[TaskViewController alloc]init];
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:taskViewController animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
- (IBAction)openExplocy:(id)sender {
    ExplocyViewController *explocyView=[[ExplocyViewController alloc] init];
    [self.navigationController pushViewController:explocyView animated:YES];
}
-(void)registerObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:CHANGEWATCH object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:UNBINDDEVICE object:nil];
}
-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CHANGEWATCH object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UNBINDDEVICE object:nil];
}
- (void)receiveNotification:(NSNotification *)sender {
    if([sender.name isEqualToString:CHANGEWATCH])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(self.view.window==NULL)
                return ;
            AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
            if(mydelegate!=NULL&&mydelegate.isAdmin==YES)
            {
                self.motherTabViewController.navigationItem.rightBarButtonItem=nil;
                UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mission_icon@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(openTask)];
                [self.motherTabViewController.navigationItem setRightBarButtonItem:rightButton];
                rightButton=NULL;
                UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"theme_icon.png"] style:UIBarButtonItemStylePlain target:self action:@selector(openTheme)];
                [self.motherTabViewController.navigationItem setLeftBarButtonItem:leftButton];
                leftButton=NULL;
            }
            else if(mydelegate!=NULL&&mydelegate.isAdmin==NO)
            {
                self.motherTabViewController.navigationItem.rightBarButtonItem=nil;
                self.motherTabViewController.navigationItem.leftBarButtonItem=nil;
            }
            [self updateData];
            [self initUiData];
            [self initThemeUi];
        });

    }
    else if([sender.name isEqualToString:UNBINDDEVICE])
    {
        if(self.view.window==NULL)
            return ;
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL&&mydelegate.isAdmin==YES)
        {
            self.motherTabViewController.navigationItem.rightBarButtonItem=nil;
            UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mission_icon@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(openTask)];
            [self.motherTabViewController.navigationItem setRightBarButtonItem:rightButton];
            rightButton=NULL;
        }
        else if(mydelegate!=NULL&&mydelegate.isAdmin==NO)
        {
            self.motherTabViewController.navigationItem.rightBarButtonItem=nil;
        }
        
        [self initUiData];
        [self initThemeUi];
    }
}

@end
